﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure.GeoLabels.Interfaces;
using VDS.RDF;
using VirtuosoDal.Repositories.RdfRepositories.Interfaces.Events;
using WebGuiMvc.Helpers.Properties;

namespace AspNetMvc.Controllers
{
   public partial class GeoLabelsController : BaseController
    {
       private readonly IGeoLabelsRepository _geoLabelsRepository;
       private readonly IGeoLabelsAdditionService _geoLabelsAdditionService;

       public GeoLabelsController(IGeoLabelsRepository geoLabelsRepository, 
          IGeoLabelsAdditionService geoLabelsAdditionService)
       {
          _geoLabelsRepository = geoLabelsRepository;
          _geoLabelsAdditionService = geoLabelsAdditionService;
       }

       [Authorize]
       [AcceptVerbs(HttpVerbs.Post)]
       public virtual JsonResult AddGeoLabel(string geoLabel, string cityUri, string cityName,
          string placeUri, string placeName)
       {
          try
          {
             if (String.IsNullOrEmpty(geoLabel))
                throw new ArgumentException("geoLabel shouldn't be null or empty");

             if (String.IsNullOrEmpty(placeUri) && String.IsNullOrEmpty(cityUri))
                return Json(new { Error = "You have to select city and/or object. Otherwise we can't determine time zone" });

             bool geoLabelExists = _geoLabelsRepository.GeoLabelExists(UserName, geoLabel);

             if (geoLabelExists)
                return
                   Json(
                      new
                      {
                         Error =
                      "You already have place with the same label. Please change the label or clear it if you dont't want to reuse this place later"
                      });

             //ToDo: Reimplement like events
             Graph graph = new Graph();
             Dictionary<string, INode> dictionary = new Dictionary<string, INode>();
             GeoLabelPropertiesParseHelper.ParseProperties(graph, dictionary,
                UserName, geoLabel, cityUri, cityName, placeUri, placeName);

             _geoLabelsAdditionService.AddGeoLabel(dictionary, graph);

             return Json(new { Success = "true" });
          }
          catch (Exception ex)
          {
             return Json(new { Error = "Some error happened. Can't add new label. Please try again later" });
          }
       }
    }
}
